package com.leonardo.tg.example;

import java.util.Vector;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;

import com.leonardo.beanme.model.BeanForm;
import com.leonardo.persistenceme.exceptions.DatabaseOpenException;
import com.leonardo.persistenceme.model.PersistenceManager;
import com.leonardo.persistenceme.model.PersistenceManagerFactory;

public class AgendaMidlet extends MIDlet {

	public static final String DB_NAME = "Agenda";
	
	protected Display display;
	private PersistenceManager pm;
	private BeanForm compromissoForm;
	private List compromissoList;
	private Vector compromissos;
//	private Compromisso test = new Compromisso();
	
//	private void Benchmark(long start, String use, double iter, Displayable next) {
//		Alert alert = new Alert("Benchmark");
//		alert.setString(use + ": " + (System.currentTimeMillis() - start)/iter);
//		alert.setTimeout(3000);
//		display.setCurrent(alert, next);
//		
//		try {
//			Thread.sleep(3000);
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
	
	public AgendaMidlet() throws DatabaseOpenException {
		this.display = Display.getDisplay(this);
		pm = PersistenceManagerFactory.getPersistenceManager(DB_NAME);
		compromissoList = new List("Lista de Compromissos", List.IMPLICIT);
		
//		pm.clearDB();
//		destroyApp(true);
	}
	
	public void destroyApp(boolean unconditional) {
		notifyDestroyed();
	}

	protected void pauseApp() { }

	protected void startApp() {
		compromissoList.addCommand(new Command("Novo", Command.OK, 1));
		compromissoList.addCommand(new Command("Editar", Command.HELP, 1));
		compromissoList.addCommand(new Command("Apagar", Command.CANCEL, 1));
		compromissoList.addCommand(new Command("Sair", Command.EXIT, 1));
		
		compromissoList.setCommandListener(new CompromissoListListener(this));
		showList();
		
//		long now = System.currentTimeMillis();
//		pm.clearDB();
//		Benchmark(now, "Clear DB", 1, compromissoList);
//		
//		test.setCompleta(Boolean.FALSE);
//		test.setConfirmada(Boolean.TRUE);
//		test.setData(new Date());
//		test.setDescricao("AAA");
//		test.setNome("compromisso");
//		now = System.currentTimeMillis();
//		for(int i = 0; i < 200; i++)
//			pm.persist(test);
//		Benchmark(now, "Persist", 200, compromissoList);
//		
//		test.setKey(new Integer(1));
//		now = System.currentTimeMillis();
//		for(int i = 0; i < 200; i++)
//			pm.update(test);
//		Benchmark(now, "Update", 200, compromissoList);
//		
//		now = System.currentTimeMillis();
//		Integer key = new Integer(2);
//		for(int i = 0; i < 200; i++)
//			pm.getByKey(key);
//		Benchmark(now, "Get by key", 200, compromissoList);
//		
//		now = System.currentTimeMillis();
//		for(int i = 0; i < 3; i++)
//			pm.listAll();
//		Benchmark(now, "List 200 entities", 3, compromissoList);
//		
//		now = System.currentTimeMillis();
//		int nEntities = pm.numPersistedEntities().intValue();
//		for(int i = 1; i <= nEntities; i++)
//			pm.delete(new Integer(i));
//		Benchmark(now, "Delete", nEntities, compromissoList);
			
		//destroyApp(true);

	}
	
	public void showList() {
		compromissoList.deleteAll();
		compromissos = pm.listAll(); 
		for(int i = 0; i < compromissos.size(); i++) { 
			String label = "";
			Compromisso compromisso = (Compromisso) compromissos.elementAt(i);
			if(Boolean.TRUE.equals(compromisso.getCompleta())) label += "Feita - ";
			if(compromisso.getNome() != null)	label += compromisso.getNome();
			if(compromisso.getData() != null)	label += " - " + compromisso.getData();
			compromissoList.insert(i, label, null);
		}
		display.setCurrent(compromissoList);
	}
	
	private void setUpForm() {
		compromissoForm.addCommand(new Command("Salvar", Command.OK, 1));
		compromissoForm.addCommand(new Command("Fechar", Command.EXIT, 1));
		compromissoForm.addCommand(new Command("Voltar para lista", Command.BACK, 1));
		compromissoForm.addCommand(new Command("Voltar para lista", Command.CANCEL, 1));
		
		compromissoForm.setCommandListener(new CompromissoFormListener(this));
		display.setCurrent(compromissoForm);
	}
	
	private void showForm(Compromisso compromisso) throws Exception {
//		long now = System.currentTimeMillis();
		compromissoForm = new BeanForm(compromisso, "Compromisso");
		setUpForm();
//		Benchmark(now, "Load and populate Form", 1, compromissoForm);
	}
	
	private void showForm() throws Exception {
//		long now = System.currentTimeMillis();
		compromissoForm = new BeanForm(Compromisso.class, "Compromisso");
		setUpForm();
//		Benchmark(now, "Load Form", 1, compromissoForm);
	}
	
	private Compromisso getSelectedCompromisso() {
		int index = compromissoList.getSelectedIndex();
		if(index < 0)
			return null;
		return (Compromisso) compromissos.elementAt(index);
	}
	
	public void delete() {
		Compromisso compromisso = getSelectedCompromisso();
		if(compromisso != null) {
			pm.delete(compromisso.getKey());
			showList();
		}
	}
	
	public void edit() {
		try {
			Compromisso compromisso = getSelectedCompromisso();
			if(compromisso != null)
				showForm(compromisso);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}
	
	public void add() {
		try {
			showForm();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}
	
	public void save() {
		try {
			Compromisso compromisso = (Compromisso) compromissoForm.getBean();
			if(compromisso.getKey() == null)
				pm.persist(compromisso);
			else if(!pm.offer(compromisso))
				pm.update(compromisso);
			showList();
		} catch (Exception e) {
			Alert alert = new Alert("Erro");
			alert.setString("Campos obrigatórios não preenchidos");
			alert.setTimeout(2000);
			display.setCurrent(alert, compromissoForm);
			e.printStackTrace();
		}
	}
}
